package com.foreveross.eimpc.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.foreveross.eimpc.web.constants.Constants;
import com.foreveross.eimpc.web.exception.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yanyuan on 2014/11/12.
 */
@Controller
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    @ExceptionHandler({RuntimeException.class, Exception.class})
    public Map<String, Object> runtimeExceptionHandler(Throwable e) {
        logger.error("系统异常: ", e);
        Map<String, Object> result = new HashMap<String, Object>();
        String errorMsg = e.getMessage();
        if(e instanceof ApiException){
            ApiException apiException = (ApiException)e;
            if(Constants.API_Internal.equals(apiException.getErrcode())){
                errorMsg = "操作失败：请求远程服务错误.";
            }else if(Constants.API_Bad_Request.equals(apiException.getErrcode())){
                result.put("errorObj", JSONObject.parseObject(apiException.getErrmsg()));
            } else {
                errorMsg = apiException.getErrmsg();
            }
        }
        result.put("error", errorMsg);
        return result;
    }

    protected String base64StringFormat(String base64Str){
        String ch = "base64,";
        return base64Str == null ? null : base64Str.substring(base64Str.indexOf(ch) + ch.length());
    }

}
